import React, { useState, useRef, useEffect } from 'react';
import {
  SyncOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  LoadingOutlined,
  CopyOutlined,
  CalendarOutlined,
  TrophyOutlined,
} from '@ant-design/icons';
import type { ProFormInstance } from '@ant-design/pro-components';
import type { UploadProps } from 'antd';

import {
  ModalForm,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
  ProFormGroup,
  ProFormList,
  ProFormDependency,
  ProTable,
  StatisticCard,
  ProCard,
} from '@ant-design/pro-components';

import {
  Button,
  Tag,
  Modal,
  message,
  Steps,
  Badge,
  Upload,
  Space,
  Alert,
  notification,
  Empty,
  Popover,
  Table,
  Collapse,
  Switch,
  Rate,
  Tooltip,
} from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { useRequest } from 'umi';
import styles from './index.less';

import MyOverview from './component/MyOverview';
import Plan from './component/Plan';
import WeekPlan from './component/WeekPlan';
import Task from './component/Task';
import MyTeamWeekPlan from './component/MyTeamWeekPlan';
import TrainingPlan from './component/TrainingPlan';
import StageNeedDone from './component/StageNeedDone';

const { Step } = Steps;
const { Panel } = Collapse;

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export default () => {
  const [tabKey, setTabKey] = useState('计划列表');
  const [stageId, setStageId] = useState();

  const TaskRef = React.createRef();

  //学生端——获取个人概览数据
  const getMyOverview = useRequest(
    (stageId = undefined) => {
      return {
        url: stageId
          ? `http://10.1.40.84:9998/stuTrain/getMyOverview?stageId=${stageId}`
          : `http://10.1.40.84:9998/stuTrain/getMyOverview`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      manual: true,
    },
  );
  //学生端——获取自己的周计划列表
  const getMyWeekPlan = useRequest(
    (stageId = null) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/getMyWeekPlan?stageId=${stageId}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      manual: true,
    },
  );
  //学生端——获取个人学习计划列表
  const getMyPlanList = useRequest(
    (stageId = null) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/getMyPlanList?stageId=${stageId}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      manual: true,
    },
  );
  useEffect(() => {
    getMyOverview.run().then((result: any) => {
      let stageStateTemp: any = result?.stageLine.filter(
        (item: any) => item.stageState === '1',
      )[0]?.id;
      setStageId(stageStateTemp);
      getMyWeekPlan.run(stageStateTemp);
    });
  }, []);
  //学生端——学生获取自己负责学生的周计划列表
  const getJuniorWeekPlan = useRequest(() => {
    return {
      url: `http://10.1.40.84:9998/stuTrain/getJuniorWeekPlan`,
      method: 'GET',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
    };
  });
  // 上传材料文件
  const props: UploadProps = {
    name: 'material',
    action: 'http://10.1.40.84:9998/stuTrain/uploadMaterial',
    headers: {
      Authorization: localStorage.getItem('token') || '',
    },
    maxCount: 1,
    // showUploadList: false,
  };
  //新建计划
  const addPlan = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/addPlan`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      onSuccess: () => {
        getMyOverview.run(stageId);
      },
    },
  );
  //学生端——获取自己的任务列表
  const getMyTask = useRequest((data = null) => {
    return {
      url: `http://10.1.40.84:9998/stuTrain/getMyTask`,
      method: 'GET',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
    };
  });

  //点击阶段切换组件，类似于tab页
  const stepOnChange = (stageItem: any) => {
    // console.log(stageItem.id);
    getMyOverview.run(stageItem.id);
    setStageId(stageItem.id);
    getMyWeekPlan.run(stageItem.id);
  };

  const openNotification = () => {
    notification.warning({
      message:
        '您有' +
        getMyWeekPlan?.data?.filter(
          (item: any) => item.weekPlanState === '未接收',
        ).length +
        '个周计划未读',
      duration: 10,
    });
  };
  useEffect(() => {
    if (
      getMyWeekPlan.data &&
      getMyWeekPlan?.data?.filter(
        (item: any) => item.weekPlanState === '未接收',
      ).length !== 0
    ) {
      openNotification();
    }
  }, [getMyWeekPlan.data]);

  const openTaskNotification = () => {
    notification.warning({
      message:
        '您有' +
        getMyTask?.data?.filter((item: any) => item.recvState === '0').length +
        '个任务未读',
      duration: 10,
    });
  };
  useEffect(() => {
    if (
      getMyTask.data &&
      getMyTask?.data?.filter((item: any) => item.recvState === '0').length !==
        0
    ) {
      openTaskNotification();
    }
  }, [getMyTask.data]);

  //给子组件引用 刷新Badge的数值
  const refreshBadge = () => {
    getMyWeekPlan.run(stageId);
    getJuniorWeekPlan.run();
    getMyTask.run();
  };

  //给子组件引用 刷新MyOverview的数值
  const refreshMyOverview = () => {
    getMyOverview.run();
  };

  return (
    <PageContainer
      content={
        <Steps style={{ paddingLeft: 30, paddingRight: 30, paddingTop: 20 }}>
          {getMyOverview?.data?.stageLine.map((item: any, index: any) => {
            if (item.stageState === '2') {
              return (
                <Step
                  status="finish"
                  key={index}
                  title={
                    <Button
                      type="dashed"
                      // className={styles.aLabel}
                      style={{ fontSize: 16 }}
                      onClick={() => {
                        stepOnChange(item);
                      }}
                    >
                      {item.stageName}
                    </Button>
                  }
                />
              );
            } else if (item.stageState === '1') {
              return (
                <Step
                  status="process"
                  key={index}
                  icon={<LoadingOutlined />}
                  title={
                    <Button
                      type="dashed"
                      // className={styles.aLabel}
                      style={{ fontSize: 16 }}
                      onClick={() => {
                        stepOnChange(item);
                      }}
                    >
                      {item.stageName}
                    </Button>
                  }
                />
              );
            } else {
              return (
                <Step
                  status="wait"
                  key={index}
                  title={
                    <Button
                      type="dashed"
                      // className={styles.aLabel}
                      style={{ fontSize: 16 }}
                      onClick={() => {
                        stepOnChange(item);
                      }}
                    >
                      {item.stageName}
                    </Button>
                  }
                />
              );
            }
          })}
        </Steps>
      }
      extra={[
        // <ModalForm
        //   key="2"
        //   title="提交阶段文件"
        //   trigger={<Button type="primary">提交阶段文件</Button>}
        //   autoFocusFirstInput
        //   modalProps={{
        //     onCancel: () => console.log('run'),
        //   }}
        //   submitTimeout={2000}
        //   onFinish={async (values) => {
        //     await waitTime(2000);
        //     console.log(values.name);
        //     message.success('提交成功');
        //     return true;
        //   }}
        // >
        //   <ProForm.Group>
        //     <ProFormSelect
        //       request={async () => [
        //         {
        //           value: '阅读文献',
        //           label: '阅读文献',
        //         },
        //         {
        //           value: '模型设计',
        //           label: '模型设计',
        //         },
        //         {
        //           value: '中期阶段',
        //           label: '中期阶段',
        //         },
        //       ]}
        //       width="md"
        //       name="type"
        //       label="所属阶段"
        //       initialValue={'中期阶段'}
        //       disabled
        //     />
        //     <ProFormText
        //       width="md"
        //       name="查阅导师"
        //       label="查阅导师"
        //       initialValue={'刘老师'}
        //       disabled
        //     />
        //     <ProFormDateRangePicker
        //       width="md"
        //       name="计划起止时间"
        //       label="计划起止时间"
        //       initialValue={[
        //         moment('2022/06/01', 'YYYY/MM/DD'),
        //         moment('2022/07/01', 'YYYY/MM/DD'),
        //       ]}
        //       disabled
        //     />
        //     <ProFormUploadButton
        //       width="sm"
        //       name="file"
        //       label="材料文件或地址"
        //       max={1}
        //       fieldProps={props}
        //       // action="/upload.do"
        //       addonAfter={<a>下载</a>}
        //     // extra="longgggggggggggggggggggggggggggggggggg"
        //     />
        //   </ProForm.Group>
        // </ModalForm>,
        <ModalForm
          key="1"
          title="增加个人计划"
          trigger={<Button type="primary">新建个人计划</Button>}
          autoFocusFirstInput
          modalProps={{
            onCancel: () => console.log('run'),
            destroyOnClose: true,
          }}
          submitTimeout={2000}
          onFinish={async (values) => {
            await waitTime(2000);
            addPlan
              .run(values)
              .then(() => {
                getMyPlanList.run(stageId);
                message.success('提交成功');
              })
              .catch(() => {
                message.error('提交失败');
              });
            return true;
          }}
        >
          <ProForm.Group>
            <ProFormText width="md" name="planName" label="计划名称" required />
            <ProFormText width="md" name="planDesc" label="计划描述" required />
            <ProFormDatePicker
              width="sm"
              name="startTime"
              label="计划开始时间"
              required
            />
            <ProFormDatePicker
              width="sm"
              name="endTime"
              label="计划终止时间"
              required
            />
            <ProFormSelect
              label="材料共享"
              name="isShareable"
              width="xs"
              valueEnum={{
                '1': '共享',
                '0': '不共享',
              }}
              required
            />
          </ProForm.Group>
          <ProFormList
            name="materialList"
            label="材料信息"
            rules={[
              {
                validator: async (_, value) => {
                  // console.log(value);
                  if (value && value.length > 0) {
                    return;
                  }
                  throw new Error('至少要有一项！');
                },
              },
            ]}
            creatorButtonProps={{
              creatorButtonText: '添加材料',
            }}
          >
            {(meta: any, index: any, action: any, count: any) => {
              return (
                <ProFormGroup key="group">
                  <ProFormText
                    width="sm"
                    required
                    name="materialName"
                    label="材料名称"
                  />
                  <ProFormSelect
                    label="材料类型"
                    name="materialType"
                    width="xs"
                    required
                    valueEnum={{
                      学习报告: '学习报告',
                      参考文献: '参考文献',
                    }}
                  />
                  <ProFormDependency name={['materialType']}>
                    {({ materialType }) => {
                      if (materialType === '参考文献') {
                        return (
                          <ProFormText
                            width="sm"
                            name="materialContent"
                            label="文献链接"
                            required
                          />
                        );
                      } else if (
                        materialType === '学习报告' ||
                        materialType === '阶段性报告'
                      ) {
                        return (
                          <>
                            <Upload
                              {...props}
                              onChange={(info) => {
                                if (info.file.status === 'done') {
                                  action.setCurrentRowData({
                                    materialContent: info.file.response.data,
                                  });
                                  message.success(
                                    `${info.file.name} 上传成功！`,
                                  );
                                } else if (info.file.status === 'error') {
                                  message.error(
                                    `${info.file.name} file upload failed.`,
                                  );
                                }
                              }}
                            >
                              <Button
                                type="link"
                                style={
                                  index === 0
                                    ? { marginTop: 30 }
                                    : { marginTop: 0 }
                                }
                              >
                                上传材料
                              </Button>
                            </Upload>
                            <ProFormText
                              width="sm"
                              name="materialContent"
                              required
                              hidden
                            />
                          </>
                        );
                      } else {
                        return null;
                      }
                    }}
                  </ProFormDependency>
                </ProFormGroup>
              );
            }}
          </ProFormList>
        </ModalForm>,
        <Badge
          key="3"
          count={
            getMyTask?.data?.filter((item: any) => item.recvState === '0')
              .length
          }
          size="small"
          overflowCount={10}
        >
          <Button
            onClick={() => TaskRef.current?.showDrawer()}
            type={'primary'}
          >
            我的任务
          </Button>
        </Badge>,
      ]}
      header={{
        title: (
          <Space size={'large'}>
            <span>个人管理</span>
            <div style={{ fontSize: 14 }}>
              <Tooltip title="当前阶段">
                <SyncOutlined spin />
              </Tooltip>
              <span style={{ marginLeft: 5 }}>
                {getMyOverview?.data?.nowStage?.stageName || '暂无阶段'}
              </span>
            </div>
            <div style={{ fontSize: 14 }}>
              <Tooltip title="提交材料个数">
                <CopyOutlined />
              </Tooltip>
              <span style={{ marginLeft: 5 }}>
                {getMyOverview?.data?.materialCount || '0'}
              </span>
            </div>
            <div style={{ fontSize: 14 }}>
              <Tooltip title="提交学习计划数量">
                <CalendarOutlined />
              </Tooltip>
              <span style={{ marginLeft: 5 }}>
                {getMyOverview?.data?.planCount || '0'}
              </span>
            </div>
            <div style={{ fontSize: 14 }}>
              <Tooltip title="提交材料平均分">
                <TrophyOutlined />
              </Tooltip>
              <span style={{ marginLeft: 5 }}>
                {getMyOverview?.data?.materialAvgScore?.toFixed(2) || '0.00分'}
              </span>
            </div>
          </Space>
        ),
      }}
    >
      {/* <StageNeedDone /> */}
      {/* <MyOverview OverviewData={getMyOverview?.data} /> */}
      <ProCard.Divider></ProCard.Divider>
      {stageId ? <TrainingPlan stageId={stageId} /> : null}
      <ProCard.Divider></ProCard.Divider>
      <ProCard
        tabs={{
          type: 'card',
          onChange: (e: any) => setTabKey(e),
        }}
      >
        <ProCard.TabPane
          key="1"
          tab="我的学习计划"
          cardProps={{ bodyStyle: { padding: 0 } }}
        >
          {stageId ? (
            <Plan
              stageId={stageId}
              PlanData={getMyPlanList.data}
              refreshMyOverview={refreshMyOverview}
            />
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          )}
        </ProCard.TabPane>

        <ProCard.TabPane
          key="2"
          tab={
            <Badge
              count={
                getMyWeekPlan?.data?.filter(
                  (item: any) => item.weekPlanState === '未接收',
                ).length
              }
              size="small"
            >
              <span style={{ fontSize: 14 }}>我的周计划</span>
            </Badge>
          }
          cardProps={{ bodyStyle: { padding: 0 } }}
        >
          <WeekPlan
            stageId={stageId}
            tabKey={tabKey}
            refreshBadge={refreshBadge}
          />
        </ProCard.TabPane>

        {getJuniorWeekPlan?.data?.length !== 0 ? (
          <ProCard.TabPane
            key="3"
            tab={
              <Badge
                count={
                  getJuniorWeekPlan?.data?.filter(
                    (item: any) => item.weekPlanState === '未接收',
                  ).length
                }
                size="small"
              >
                <span style={{ fontSize: 14 }}>我的小组周计划</span>
              </Badge>
            }
            cardProps={{ bodyStyle: { padding: 0 } }}
          >
            <MyTeamWeekPlan stageId={stageId} refreshBadge={refreshBadge} />
          </ProCard.TabPane>
        ) : null}
      </ProCard>
      <Task onRef={TaskRef} refreshBadge={refreshBadge} />
    </PageContainer>
  );
};
